﻿using System;
using System.Collections.Generic;
using UnityEngine;

namespace ET
{
	[ActorMessageHandler]
	public class G2M_CreateUnitHandler : AMActorRpcHandler<Scene, G2M_CreateUnit, M2G_CreateUnit>
	{
		protected override async ETTask Run(Scene scene, G2M_CreateUnit request, M2G_CreateUnit response, Action reply)
		{
			//创建Unity
			Unit unit = EntityFactory.CreateWithId<Unit, int>(scene, IdGenerater.Instance.GenerateId(), 1001);
			
			long dbCacheId = StartSceneConfigCategory.Instance.GetBySceneName(scene.DomainZone(), Enum.GetName(SceneType.DBCache)).SceneId;
			
			D2G_GetUnit d2GGetUnit = (D2G_GetUnit)await ActorMessageSenderComponent.Instance.Call(dbCacheId, new G2D_GetUnit(){CharacterId = request.CharacterId});

			for (int i = 0; i < d2GGetUnit.Components.Count; i++)
			{
				unit.AddComponent(d2GGetUnit.Components[i]);
			}

			TCharacter character = unit.GetComponent<TCharacter>();
			character.DBCacheId = request.DBCacheId;


			unit.AddComponent<MailBoxComponent>();

			await unit.AddLocation();

			unit.AddComponent<UnitGateComponent, long>(request.GateSessionId);

			scene.GetComponent<UnitComponent>().Add(unit);
			
			response.UnitId = unit.Id;
			response.Unit = UnitHelper.CreateUnitInfo(unit);

			reply();
		}
	}
}